package com.ctgu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.dao.dto.GroupDto;
import com.ctgu.server.dao.dto.GroupUserDto;
import com.ctgu.server.dao.entity.Group;
import com.ctgu.server.dao.entity.GroupRole;
import com.ctgu.server.dao.entity.GroupUser;
import com.ctgu.server.dao.entity.User;
import com.ctgu.server.dao.vo.GroupUserVo;
import com.ctgu.server.dao.vo.GroupVo;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.dao.vo.UserVo;
import com.ctgu.server.mapper.GroupMapper;
import com.ctgu.server.mapper.UserMapper;
import com.ctgu.server.service.GroupRoleService;
import com.ctgu.server.service.GroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.server.service.GroupUserService;
import com.ctgu.server.service.UserService;
import com.ctgu.server.utils.ResultUtil;
import com.github.dozermapper.core.Mapper;
import net.oschina.j2cache.CacheChannel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ctgu
 * @since 2023-05-17
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService {
    @Autowired
    private GroupUserService groupUserService;

    @Autowired
    private GroupRoleService groupRoleService;

    @Autowired
    private UserService userService;
    @Autowired
    private Mapper mapper;

    @Autowired
    private CacheChannel cacheChannel;


    @Override
    public Result addGroupRole(String userId, String groupId) {
        //1.查询该组织是否存在
        Group group= this.getById(groupId);
        if (group== null){
            return ResultUtil.error("错误的邀请码");
        }
        //2.查询该用户是否已经存在于该组织
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(GroupUser::getGroupId,groupId)
                .eq(GroupUser::getUserId,userId);
        GroupUser groupUser= groupUserService.getOne(lambdaQueryWrapper,false);
        if(groupUser!=null){
            return ResultUtil.success("用户已加入，无需重复加入");
        }
        //3.将该用户的信息加入到该组织
        groupUser=new GroupUser();
        groupUser.setGroupRoleId("2");
        groupUser.setUserId(userId);
        groupUser.setGroupId(groupId);
        groupUser.setIsAdmin(false);
        groupUserService.save(groupUser);
        return ResultUtil.success("成功加入："+group.getGroupName());
    }

    /**
    *获取组织用户列表的的信息
    * */
    @Override
    public List<GroupVo> getUserList(String id) {

        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
         lambdaQueryWrapper.eq(GroupUser::getUserId,id);
         List<GroupUser> list= groupUserService.list(lambdaQueryWrapper);
         List<GroupVo> res=new ArrayList<>();
        for(GroupUser groupUser:list){
            //查询用户在该组织的所有信息
            //todo 后续优化该位置的查询方式，
            Group group= this.getById(groupUser.getGroupId());
            GroupRole groupRole=groupRoleService.getById(groupUser.getGroupRoleId());
            GroupVo groupVo=mapper.map(group, GroupVo.class);
            //处理结果
            groupVo.setIsAdmin(groupUser.getIsAdmin());
            //角色身份可能为空
            if(groupRole!=null){
                groupVo.setIdentify(groupRole.getIdentify());
            }

            res.add(groupVo);
        }
        return res;
    }

    @Override
    public Result createGroup(String userId, String groupName) {
        //查询当前用户已经创建了几个组织，最大创建三个组织
        LambdaQueryWrapper<Group> groupUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        groupUserLambdaQueryWrapper.eq(Group::getUserId,userId);
        if(this.count(groupUserLambdaQueryWrapper)>5){//每个人最多创建五个组织
            return ResultUtil.error("创建组织数已达到上限5");
        }
        //为用户创建组织
        Group group=new Group();
        group.setUserId(userId);
        group.setGroupName(groupName);
        this.save(group);
        //查询新创建的组织信息
        groupUserLambdaQueryWrapper.eq(Group::getGroupName,groupName);
        Group group1= this.getOne(groupUserLambdaQueryWrapper,false);
        if(group1==null){
            return ResultUtil.error("系统错误,创建新组织失败！");
        }
        //将创建者添加到组织成员中
        GroupUser groupUser=new GroupUser();
        groupUser.setGroupId(group1.getGroupId());
        groupUser.setUserId(userId);
        groupUser.setGroupRoleId("2");
        groupUser.setIsAdmin(true);
        groupUserService.save(groupUser);

        return ResultUtil.success("创建"+groupName+"成功");


    }

    @Override
    public Result deleteGroupUser(String userId, String groupId) {
        //1.查询该组织是否存在
        Group group= this.getById(groupId);
        if(group==null){
            return ResultUtil.error("参数错误，未找到目标组织");
        }


        if ( StringUtils.equals(group.getUserId(), userId)) {
            //组织所有者不允许退出组织，或者被踢
            return ResultUtil.error("组织所有者不允许离开组织");
        }
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(GroupUser::getGroupId,groupId)
                .eq(GroupUser::getUserId,userId);
        groupUserService.remove(lambdaQueryWrapper);
        return ResultUtil.success("请求成功！");
    }

    @Override
    public Result deleteGroupList(String userId, String groupId) {
        Group group=this.getById(groupId);
        if(group==null){
            return ResultUtil.error("目标组织不存在");
        }
        if( !StringUtils.equals(group.getUserId(), userId)){
            return ResultUtil.error("用户无权限操作该组织");
        }
        //删除组织信息
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupUser::getGroupId,groupId);
        groupUserService.remove(lambdaQueryWrapper);
        //删除组织成员信息
        LambdaQueryWrapper<GroupRole> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(GroupRole::getGroupId,groupId);
        groupRoleService.remove(lambdaQueryWrapper1);
        //删除组织
        this.removeById(groupId);
        return ResultUtil.success("解散组织成功");
    }

    @Override
    public Result deleteByAdmin(String userId, String opId, String groupId) {
        Group group=this.getById(groupId);
        if(group==null|| StringUtils.equals(group.getUserId(), userId)){
            return ResultUtil.error("组织所有者禁止被踢");
        }
        //查询操作者是否拥有权限
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupUser::getGroupId,groupId).eq(GroupUser::getUserId,opId).eq(GroupUser::getIsAdmin,1);
        if (groupUserService.getOne(lambdaQueryWrapper,false)==null) {
            return ResultUtil.error("用户不具有操作权限");
        }
        //当用户有权限时，开始删除被踢用户
        lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupUser::getGroupId,groupId).eq(GroupUser::getUserId,userId).eq(GroupUser::getIsAdmin,0);
        boolean flag= groupUserService.remove(lambdaQueryWrapper);
        if(flag){
            return ResultUtil.success("删除成功！");
        } else {
            return ResultUtil.error("删除失败，管理员无法删除管理员");
        }
    }

    @Override
    public Result updateGroupUser(GroupUserDto groupUserDto) {
        //1.查询用户是否拥有管理员权限
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupUser::getGroupId,groupUserDto.getGroupId())
                .eq(GroupUser::getUserId,groupUserDto.getOpId())
                .eq(GroupUser::getIsAdmin,true);

        if( groupUserService.getOne(lambdaQueryWrapper,false)==null){
            return ResultUtil.error("无权限修改改成员信息");
        }
        //2.修改成员信息
        LambdaUpdateWrapper<GroupUser> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .eq(GroupUser::getGroupId,groupUserDto.getGroupId())
                .eq(GroupUser::getUserId,groupUserDto.getUserId());
        GroupUser groupUser=mapper.map(groupUserDto,GroupUser.class);
        groupUserService.update(groupUser,lambdaUpdateWrapper);
        return ResultUtil.success("成员信息修改成功！");
    }

    @Override
    public Result getGroupUser(String groupId) {

        //1.查询缓存
        List<GroupUserVo> groupUserVos= (List<GroupUserVo>) cacheChannel.get(CacheKey.Group_Redis,groupId.toString()).getValue();
        if(groupUserVos!=null){
            return ResultUtil.success(groupUserVos);
        }
        groupUserVos=new LinkedList<>();

        //查询该组织的所有成员
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GroupUser::getGroupId,groupId);
        List<GroupUser> groupUserList=groupUserService.list(lambdaQueryWrapper);
        //查询该组织的所有身份
        LambdaQueryWrapper<GroupRole> roleLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(GroupRole::getGroupId,groupId);
        List<GroupRole> groupRoleList=groupRoleService.list(roleLambdaQueryWrapper);

        //处理参数
        for(GroupUser groupUser:groupUserList){
            GroupUserVo groupUserVo=mapper.map(groupUser,GroupUserVo.class);
            groupUserVo.setUserVo(mapper.map(userService.getById(groupUser.getUserId()), UserVo.class));
            for(GroupRole groupRole:groupRoleList){
                //如果身份相同
                if(Objects.equals(groupUser.getGroupRoleId(), groupRole.getId())){
                    groupUserVo.getUserVo().setIdentify((groupRole.getIdentify()));
                    break;
                }
            }
            if(groupUserVo.getUserVo().getIdentify()==null){
                groupUserVo.getUserVo().setIdentify("成员");
            }
            groupUserVos.add(groupUserVo);
        }

        //将其放到缓存中
        cacheChannel.set(CacheKey.Group_Redis,groupId.toString(),groupUserVos);
        return ResultUtil.success(groupUserVos);

    }
    /**
     * @param userId:
     * @param groupDto:
     * @return Result
     * @author kvzjj
     * @description TODO
     * @date 2023/6/5 15:40
     */
    @Override
    public Result updateGroupInfo(String userId, GroupDto groupDto) {
        //1.查询当前组织是否存在
        Group group= this.getById(groupDto.getGroupId());
        if(group==null){
            return ResultUtil.error("未查询到目标组织");
        }
        LambdaQueryWrapper<GroupUser> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
         lambdaQueryWrapper1.eq(GroupUser::getUserId,userId).eq(GroupUser::getGroupId,groupDto.getGroupId());
         GroupUser groupUser= groupUserService.getOne(lambdaQueryWrapper1,false);
        //2.查看当前用户是否有修改权限
        if(!groupUser.getIsAdmin()){
            return ResultUtil.error("用户无权限修改组织信息");
        }
        //3.如果拥有权限
        Group group1=mapper.map(groupDto, Group.class);
        //且打算修改组织所有者时
        if(groupDto.getUserName()!=null){
            //4.查询目标用户是否存在
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getUserName,groupDto.getUserName());
            User user=userService.getOne(lambdaQueryWrapper,false);
            if(user==null){
                //不存在
                return ResultUtil.error("未查询到账户名:"+groupDto.getUserName());
            }
            //当目标用户存在时
            group1.setUserId(user.getId());

        }else {
            //当用户没有打算修改创建者时
            group1.setUserId(group.getUserId());
        }
        this.updateById(group1);
        return ResultUtil.success("修改成功",group1);
    }
}
